package com.yb.xczx.cloud.passport.config;

import com.yb.xczx.cloud.oauth2.client.bean.XczxOauth2ClientProperties;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/19 16:02
 * FileName: FeignConfig
 * Description:
 */

@Slf4j
public class FeignConfig {

    private final String AUTHORIZATION_HEADER = "Authorization";
    private final String BASIC_TOKEN_TYPE = "Basic";
    //拦截器，每次访问在header里添加token

    private final String BASIC_HEADER_PATTERN="%s:%s";

    private XczxOauth2ClientProperties clientProperties;
    public FeignConfig(XczxOauth2ClientProperties clientProperties){
        this.clientProperties=clientProperties;
    }


    @Bean
    RequestInterceptor requestInterceptor(){
        log.info("clientProperties:{}",clientProperties);
        byte[] encode = Base64.getEncoder().encode(String.format(BASIC_HEADER_PATTERN, clientProperties.getAuth().getClientId(), clientProperties.getAuth().getClientSecret()).getBytes(StandardCharsets.UTF_8));
        String basicHeaderValue=new String(encode);
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {

                    requestTemplate.header(AUTHORIZATION_HEADER,String.format("%s %s",BASIC_TOKEN_TYPE, basicHeaderValue));
                    requestTemplate.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
            }
        };
    }
}
